#!/usr/bin/env python3
import os
import json
import curses
import curses.textpad
import traceback
import shutil
from window_tree_node import WindowTreeNode, CommandWindow

DEFAULT_CLOGS_LOCATION = '.local/share/strlst/default.clogs'

def grab_input(window):
    while True:
        return window.getch()

def read_logs(filepath):
    shutil.copyfile(filepath, f'{filepath}.bak')
    with open(filepath, 'r') as f:
        return json.load(f)

def write_logs(filepath, logs):
    with open(filepath, 'w') as f:
        json.dump(logs, f)

def main(stdscr):
    filepath = f'{os.getenv("HOME")}/{DEFAULT_CLOGS_LOCATION}'
    logs = read_logs(filepath)
    state = {
        'stdscr': stdscr,
        'logs': logs,
        'filepath': filepath,
        'write_callback': write_logs,
        'quit': False,
        'write': False
    }

    curses.use_default_colors()
    curses.curs_set(0)
    max_nl, max_nc = stdscr.getmaxyx()

    cmd = CommandWindow(1, max_nc, max_nl - 1, 0)
    root = WindowTreeNode(cmd, max_nl - 1, max_nc - 1, max_nl - 1, max_nc - 1, 0, 1, logs, active=True, display_metadata=True)
    
    while not state['quit']:
        # render current state
        cmd.render()
        root.render()

        # grab new input
        keypress = grab_input(root.window)

        # update based on input
        root.update(state, keypress)
        cmd.update(state, keypress)

if __name__ == '__main__':
    try:
        curses.wrapper(main)
    except Exception:
        traceback.print_exc()
